<?php


class Auth_admin
{
		
	/**
     * 用户
     *
     * @access private
     * @var array
     */
    private $_admin = array();
    
    /**
     * 是否已经登录
     * 
     * @access private
     * @var boolean
     */
    private $_hasLogin = NULL;
	
	/**
    * CI句柄
    * 
    * @access private
    * @var object
    */
	private $_CI;
	
	public function __construct()
	{
		        /** 获取CI句柄 */
		$this->_CI = & get_instance();
		$this->_CI->load->model('admins_mdl','admin');
		$this->_admin = unserialize($this->_CI->session->userdata('admin'));
		
	}
	
    /**
     * 判断用户是否已经登录
     *
     * @access public
     * @return void
     */
	public function hasLogin()
	{
		/** 检查session，并与数据库里的数据相匹配 */
		if (NULL !== $this->_hasLogin)
		{
            return $this->_hasLogin;
        }
		else 
		{
			if(!empty($this->_admin) && NULL !== $this->_admin['uid'])
			{
				$admin = $this->_CI->admin->get_admin_by_id($this->_admin['uid']);
				
				if($admin && $admin['token'] == $this->_admin['token'])
				{
					
					$this->_CI->admin->update_admin($this->_admin['uid'],$admin);
					
					return ($this->_hasLogin = TRUE);
				}
			}
			
			return ($this->_hasLogin = FALSE);
		}
	}
	
	/**
     * 处理用户登录
     *
     * @access public
     * @param  array $user 用户信息
     * @return boolean
     */
	public function process_login($admin)
	{
		/** 获取用户信息 */
		$this->_admin = $admin;
		
		/** 每次登陆时需要更新的数据 */
		$this->_admin['lastlogin'] = time();
		/** 每登陆一次更新一次token */
		$this->_user['token'] = sha1(time().rand());
		
		if($this->_CI->admin->update_admin($this->_admin['uid'],$this->_admin))
		{
			/** 设置session */
			$this->_set_session();
			$this->_hasLogin = TRUE;
			
			return TRUE;
		}
		
		return FALSE;
	}
	
	/**
	 * 判断登录
	 * @access public
	 * 
	 */
	
	public function check_login()
	{
		$admin = $this->_CI->session->userdata('admin');
		if(empty($admin))
		{
			redirect('adminroot/login');
		}
	}
	
	/**
     * 设置session
     *
     * @access private
     * @return void
     */
	private function _set_session() 
	{
		$session_data = array('admin' => serialize($this->_admin));
		
		$this->_CI->session->set_userdata($session_data);
	}
	
	 /**
     * 处理用户登出
     * 
     * @access public
     * @return void
     */
	public function process_logout()
	{
		$this->_CI->session->sess_destroy();
		
		//redirect('adminroot/login');
		myredirect(site_url('adminroot/login'));
		
	}
	
}